import { Vector2 } from "../vector";  
import { Engine } from "../engine";  
import { CameraEffect } from "./camera-effect";  
  
export class CameraManager {  
  private engine: Engine;  
  private effects: CameraEffect[] = [];  
  private originalUpdateFn: () => void;  
  
  constructor(engine: Engine) {  
    this.engine = engine;  
    
    setTimeout(()=>{
        this.originalUpdateFn = engine.camera.update_;  
        
        // 替换相机更新函数  
        engine.camera.update_ = () => this.update();  
        console.log("CameraManager init",engine);
    },100);
  }  
  
  addEffect(effect: CameraEffect): void {  
    this.effects.push(effect);  
  }  
  
  removeEffect(effect: CameraEffect): void {  
    const index = this.effects.indexOf(effect);  
    if (index > -1) {  
      this.effects.splice(index, 1);  
    }  
  }  
  
  clearEffects(): void {  
    this.effects.forEach(effect => effect.stop());  
    this.effects = [];  
  }  
  
  private update(): void {  
    // 先执行原始的相机更新逻辑  
    this.originalUpdateFn.call(this.engine.camera);  
      
    // 获取基础相机位置  
    let finalPos = this.engine.camera.pos.copy();  
  
    // 应用所有激活的运镜效果  
    for (const effect of this.effects) {  
      if (effect.isActive) {  
        finalPos = effect.apply(finalPos);  
          
        // 移除已完成的效果  
        if (effect.isFinished) {  
          effect.stop();  
        }  
      }  
    }  
  
    // 清理已完成的效果  
    this.effects = this.effects.filter(effect => effect.isActive);  
  
    // 应用最终位置  
    this.engine.camera.pos = finalPos;  
  }  
  
  destroy(): void {  
    this.engine.camera.update_ = this.originalUpdateFn;  
    this.clearEffects();  
  }  
}